package Java8实战._1_并行流;

import Java8实战._1_并行流._3_正确使用并行流.Accumulator;

import java.util.stream.LongStream;
import java.util.stream.Stream;

public class ParallelStreams {

    /**
     * 传统方法
     * @param n
     * @return
     */
    public static long iterativeSum(long n){
        long result = 0;
        for (long i = 1L; i <= n; i++){
            result = result + i;
        }
        return result;
    }


    /**
     * 顺序流1
     * @param n
     * @return
     */
    public static long sequentialSum(long n){
        return Stream.iterate(1L, i -> i + 1)
                .limit(n)
                .reduce(0L, Long::sum);
    }

    /**
     * 并行流1
     * @param n
     * @return
     */
    public static long parallelSum(long n){
        return Stream.iterate(1L, i -> i + 1)
                .limit(n)
                .parallel()
                .reduce(0L, Long::sum)
                ;
    }

    /**
     * 顺序流2
     * @param n
     * @return
     */
    public static long rangedSum(long n) {
        return LongStream.rangeClosed(1,n)
                .reduce(0L, Long::sum)
                ;
    }

    public static long parallelRangedSum(long n){
        return LongStream.rangeClosed(1,n)
                .parallel()
                .reduce(0L,Long::sum)
                ;
    }


    public static long sideEffectParallelSum(long n){
        Accumulator accumulator = new Accumulator();
        LongStream.rangeClosed(1,n).parallel().forEach(accumulator::add);
        return accumulator.total;
    }

}



















